import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk
import requests
import io

# 创建主窗口
class PhotoApp:
    def __init__(self, root):
        self.root = root
        self.root.title("每日图片查看器")
        self.root.geometry("1920x1080")

        # 创建一个标签用于显示图片
        self.image_label = tk.Label(root)
        self.image_label.pack(pady=20)

        # 创建一个按钮用于获取图片
        self.get_photo_button = tk.Button(root, text="获取今日图片", command=self.fetch_photo)
        self.get_photo_button.pack(pady=10)

    def fetch_photo(self):
        try:
            # 请求 API 获取图片 URL
            response = requests.get("https://dayu.qqsuu.cn/moyuribao/apis.php?type=json")
            if response.status_code == 200:
                data = response.json()
                image_url = data.get("data")
                if image_url:
                    self.display_image(image_url)
                else:
                    messagebox.showwarning("警告", "未找到图片数据！")
            else:
                messagebox.showerror("错误", f"请求失败，状态码：{response.status_code}")
        except Exception as e:
            messagebox.showerror("错误", f"请求失败！\n错误信息：{e}")

    def display_image(self, image_url):
        try:
            # 下载图片
            image_response = requests.get(image_url)
            if image_response.status_code == 200:
                # 使用 PIL 加载图片
                image = Image.open(io.BytesIO(image_response.content))
                photo = ImageTk.PhotoImage(image)

                # 显示图片
                self.image_label.config(image=photo)
                self.image_label.image = photo  # 防止图片被垃圾回收
            else:
                messagebox.showerror("错误", f"无法下载图片，状态码：{image_response.status_code}")
        except Exception as e:
            messagebox.showerror("错误", f"无法加载图片！\n错误信息：{e}")

if __name__ == "__main__":
    root = tk.Tk()
    app = PhotoApp(root)
    root.mainloop()